export function toast(content) {
    uni.showToast({
        icon: 'none',
        title: content
    });
}

export function showConfirm(content) {
    return new Promise((resolve, reject) => {
        uni.showModal({
            title: '提示',
            content: content,
            cancelText: '取消',
            confirmText: '确定',
            success: function(res) {
                resolve(res);
            }
        });
    });
}

export function tansParams(params) {
    let result = '';
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        var part = encodeURIComponent(propName) + '=';
        if (value !== null && value !== '' && typeof(value) !== 'undefined') {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && value[key] !== '' && typeof(value[key]) !== 'undefined') {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + '=';
                        result += subPart + encodeURIComponent(value[key]) + '&';
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + '&';
            }
        }
    }
    return result;
}

export function getPageConfig(pageCode) {
    return pageConfig[pageCode];
}

export function initFormData(items) {
    let dataObj = {};
    items.forEach(item => {
        if (item.isShow) {
            if (item.key.indexOf('.') !== -1) {
                _.set(dataObj, item.key, item.value);
            } else {
                dataObj[item.key] = item.value;
            }
        }
    });
    return dataObj;
}

export function setItems(formItemList, key, items) {
    let index = formItemList.findIndex((e) => {
        return e.key === key;
    });
    if (index > -1 && items.length > 0) {
        formItemList[index].items = items;
    } else {
        formItemList[index].items = [];
    }
}

function getNestedValue(obj, path) {
    if (!path.includes('.')) return obj[path];
    return path.split('.').reduce((acc, key) => acc && acc[key], obj);
}

export function handleItems(data, textKey, valueKey) {
    return data.map(item => ({
        text: getNestedValue(item, textKey),
        value: getNestedValue(item, valueKey)
    }));
}